package com.bw.ppx.frame;

import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.FragmentNavigator;

import com.bw.ppx.frame.appconfig.AppConfig;
import com.bw.ppx.frame.entity.DestinationEntity;

import java.util.HashMap;
import java.util.Iterator;

/**
 * 根据服务器假发json  destination.json  动态添加fragment
 * */
public class NavigationBuilder {
    public void create(FrameActivity activity,
                       FragmentManager manager,
                       NavController controller,
                       int contentId){
        NavigatorProvider provider = controller.getNavigatorProvider();
        NavGraph navGraph = new NavGraph(new NavGraphNavigator(provider));
        Navigator navigator = new Navigator(activity, manager, contentId);
        provider.addNavigator(navigator);
        HashMap<String, DestinationEntity> map = AppConfig.getInstance().destinationMap;
        Iterator<String> iterator = map.keySet().iterator();//map生成为迭代器
        while (iterator.hasNext()){
            String key = iterator.next();
            DestinationEntity destinationEntity = map.get(key);
            FragmentNavigator.Destination destination = navigator.createDestination();
            destination.setClassName(destinationEntity.className);
            destination.setId(destinationEntity.id);
            destination.addDeepLink(destinationEntity.pageUrl);
            navGraph.addDestination(destination);
            if (destinationEntity.asStarter)
                navGraph.setStartDestination(destinationEntity.id);
        }

        controller.setGraph(navGraph);
    }
}
